﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using springProject.Models;
using System.Data.Objects;
using System.Reflection;
using System.Data.Objects.DataClasses;
using NHibernate;

namespace Models.DataAccess
{
    public class Repository : IRepository
    {
        private readonly ISession session;

        public Repository()
        {
            this.session = NHibernateHelper.OpenSession();
        }

        public List<T> GetAll<T>()
        {
            List<T> temp;
            using (var transasction = session.BeginTransaction())
            {
                temp = new List<T>(session.CreateCriteria(typeof(T)).List<T>());
            }
            return temp;
        }

        public T GetById<T>(Guid id)
        {
            T item;
            using (var transasction = session.BeginTransaction())
            {
                item = session.Get<T>(id);
                //session.Clear();                
            }
            return item;
        }

        public void Save<T>(T item)
        {

            using (var transasction = session.BeginTransaction())
            {
                session.Save(item);
                transasction.Commit();
            }
        }

        public void Update<T>(T item)
        {
            session.Clear();
            using (var transasction = session.BeginTransaction())
            {
                session.Update(item);
                transasction.Commit();
            }
        }

        public void Delete<T>(T item)
        {
            using (var transasction = session.BeginTransaction())
            {
                session.Delete(item);
                transasction.Commit();
            }
        }
    }
}